package br.com.osmosisenglish;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.osmosisenglish.jdo.PersistenceHelper;
import br.com.osmosisenglish.jdo.Subscription;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class SendWordsJobServlet extends HttpServlet {
	SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
	
    public void doGet(HttpServletRequest req, HttpServletResponse res)
          throws IOException {

    	StringBuffer buff = new StringBuffer();

		Properties vocabulary = new Properties(); 
		vocabulary.load(getServletContext().getResourceAsStream("/WEB-INF/vocabulary.properties"));

		Object[] words = (Object[]) vocabulary.keySet().toArray();
		Arrays.sort(words);

		Random random = new Random();
    	buff.append("\n------ Words (")
			.append(sdf.format(new Date()))
			.append(")\n\n.  ")
    		.append(words[random.nextInt(words.length-1)])
			.append("\n.  ")
    		.append(words[random.nextInt(words.length-1)])
			.append("\n.  ")
    		.append(words[random.nextInt(words.length-1)])
			.append("\n");

		
		//---
		PersistenceManager pm = PersistenceHelper.getPersistenceManager();
		JID[] jids = null;
		try {
			Query query = pm.newQuery(Subscription.class);
			List<Subscription> subs = (List<Subscription>)query.execute();
			if (subs.size()==0) {
				return;
			}
			
			jids = new JID[subs.size()];
			for (int i = 0; i < jids.length; i++) {
				jids[i] = new JID(subs.get(i).getEmail());
			}
		} finally {
			pm.close();
		}

    	XMPPService xmpp = XMPPServiceFactory.getXMPPService();
    	for (int i = 0; i < jids.length; i++) {
            if (xmpp.getPresence(jids[i]).isAvailable()) {
                Message msg = new MessageBuilder()
	                .withRecipientJids(jids[i])
	                .withBody(buff.toString())
	                .build();
            	
                SendResponse status = xmpp.sendMessage(msg);
                boolean messageSent = (status.getStatusMap().get(jids[i]) == SendResponse.Status.SUCCESS);
                if (!messageSent) {
                	log(">> Message to " + jids[i].getId() + " not sent.");
                }        	
            }
		}           	
    }

}